﻿Imports MySql.Data.MySqlClient

Public Class MySQL
    Private m_ConnectString As String

    'Private Shared ReadOnly m_lock As New Object()

    Public Sub New(connectString As String)
        m_ConnectString = connectString
    End Sub

    Public Function Query(sqlQuery As String) As List(Of Dictionary(Of String, Object))
        Dim connection = New MySqlConnection(m_ConnectString)
        connection.Open()
        Dim objCommand As New MySqlCommand(sqlQuery, connection)
        Dim objDataReader As MySqlDataReader = objCommand.ExecuteReader

        Dim results As New List(Of Dictionary(Of String, Object))
        If objDataReader IsNot Nothing Then
            While objDataReader.Read()
                Dim DictionaryOf_Line As New Dictionary(Of String, Object)

                For i = 0 To objDataReader.FieldCount - 1
                    Dim valeur = objDataReader(i)

                    If TypeOf valeur Is DBNull Then valeur = Nothing

                    DictionaryOf_Line.Add(objDataReader.GetName(i), valeur)
                Next

                results.Add(DictionaryOf_Line)
            End While
        End If

        connection.Close()

        Return results
    End Function

    Public Sub QueryAsync(sqlQuery As String, Optional callback As Action(Of List(Of Dictionary(Of String, Object))) = Nothing)
        Dim connection = New MySqlConnection(m_ConnectString)
        connection.Open()
        Dim objCommand As New MySqlCommand(sqlQuery, connection)
        Dim objDataReader As MySqlDataReader = objCommand.ExecuteReader

        Dim results As New List(Of Dictionary(Of String, Object))
        If objDataReader IsNot Nothing Then
            While objDataReader.Read()
                Dim DictionaryOf_Line As New Dictionary(Of String, Object)

                For i = 0 To objDataReader.FieldCount - 1
                    Dim valeur = objDataReader(i)

                    If TypeOf valeur Is DBNull Then valeur = Nothing

                    DictionaryOf_Line.Add(objDataReader.GetName(i), valeur)
                Next

                results.Add(DictionaryOf_Line)
            End While
        End If

        connection.Close()

        If Not IsNothing(callback) Then callback(results)
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
End Class